package com.jintian.smart.kernel.orm.context;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.jintian.smart.kernel.core.orm.IBizTableContext;
import org.apache.commons.beanutils.PropertyUtils;

@SuppressWarnings("rawtypes")
public class BizTableContextImpl implements IBizTableContext, Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private final Map<String, List> bizTables;

	public BizTableContextImpl(Map<String, List> bizTables) {
		this.bizTables = bizTables;
	}

	public List getTable(String name) {
		return bizTables.get(name.toUpperCase());

	}

	public int getCount(String name) {
		List list = this.getList(name);
		return list.size();
	}

	public boolean isNull(String name, String prop) throws Exception {
		List list = this.getList(name);
		if (list.isEmpty()) {
			return true;
		}
		Object bean = list.get(0);
		return PropertyUtils.getProperty(bean, prop) == null;
	}

	public Object getValue(String name, String prop) throws Exception {
		List list = this.getList(name);
		if (list.isEmpty()) {
			return null;
		}
		Object bean = list.get(0);
		return PropertyUtils.getProperty(bean, prop);
	}

	public Object exists(String name, List<String> props, List<Object> values) throws Exception {
		List list = this.getList(name);
		for (Object bean : list) {
			for (int idx = 0; idx < props.size(); idx++) {
				String prop = props.get(idx);
				if (!Objects.equals(PropertyUtils.getProperty(bean, prop), values.get(idx))) {
					return false;
				}
			}
			return true;
		}
		return false;
	}

	public Object first(String name, List<String> props, List<Object> values) throws Exception {
		List list = this.getList(name);
		for (Object bean : list) {
			boolean eq = true;
			for (int idx = 0; idx < props.size(); idx++) {
				String prop = props.get(idx);
				if (!Objects.equals(PropertyUtils.getProperty(bean, prop), values.get(idx))) {
					eq = false;
					break;
				}
			}
			if (eq) {
				return bean;
			}
		}
		return null;
	}

	private List getList(String name) {
		List list = bizTables.get(name.toUpperCase());
		if (list == null) {
			throw new IllegalArgumentException("数据" + name + "不存在");
		}
		return list;
	}

}
